/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from 'react'
import {message, Button, Modal, Input, Form, Alert, Select } from 'antd'
import axios from "../../../../apis/api";
import qs from "qs";
import {connect} from "react-redux";
import {accSub} from '../../../../utils/number'
import md5 from 'md5-node'
import PropTypes from "prop-types"

const { Option } = Select

const mapStateToProps = (state, ownProps) => {
    return {
        user: state.main.user
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
    }
}

const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};

class SettlementApplyForm extends Component {

    state = {
        vwBusinessCashStat: {},
        businessCaptialSetting: {},
        bankInfos: [],
        loading: false
    }

    static propTypes = {
        handleApplyOk: PropTypes.func,
        inDlg: PropTypes.bool
    }

    static defaultProps = {
        handleApplyOk: () => {
        },
        inDlg: false
    }

    componentDidMount() {
        this.initData()
    }
    initData = async () => {
        try {
            const result = await axios.get('/channel/businessCapital//withdraw/info')
            if (result.code === 0) {
                this.setState({...result.data})
            } else {
                message.error(result.msg)
            }
        } catch (e) {
            message.error(e.message || e.msg)
            console.log(e)
        }
    }

    renderAlertMessage = () => {
        const {vwBusinessCashStat, businessCaptialSetting} = this.state
        const message = (
            <span style={{fontSize: 16}}>
                <span style={{color: 'red'}}>可提现金额¥:&nbsp;{vwBusinessCashStat.cashSum}</span>
                <span>&nbsp;&nbsp;冻结金额¥:&nbsp;{vwBusinessCashStat.frzzingCash}</span>
                <span style={{color: 'red'}}>&nbsp;&nbsp;单笔最低金额:&nbsp;{businessCaptialSetting.minAmount}</span>
                <span style={{color: 'red'}}>&nbsp;&nbsp;单笔最高金额:&nbsp;{businessCaptialSetting.maxAmount}</span>
            </span>
        )
        return <Alert message={message} type="warning" />
    }
    handleSubmit = (e) => {
        e.preventDefault()
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                this.setState({
                    loading: true
                })
                const {cash, cashTure, rate, card, remark, password} = values
                if (cash <= rate) {
                    message.error('提现金额需大于手续费')
                    this.setState({
                        loading: false
                    })
                    return
                }
                try {
                    const result = await axios.get(`/channel/businessInfo/checkPassword1?password=${md5(password)}`)
                    if (!result) {
                        message.error('请输入正确的密码')
                        this.setState({
                            loading: false
                        })
                        return
                    }
                    const applyResult = await axios.post('/channel/businessCapital/withdraw', qs.stringify({
                        amount: cash,
                        bank: card,
                        remark: remark,
                        password: md5(password),
                        fee: rate,
                        realAmount: cashTure,
                    }))
                    if (applyResult.code === 0) {
                        message.success('已提交成功，等待审核！')
                        this.setState({
                            loading: false
                        })
                        this.props.handleApplyOk()
                    } else {
                        this.setState({
                            loading: false
                        })
                        message.error(applyResult.msg)
                    }
                } catch (e) {
                    this.setState({
                        loading: false
                    })
                    console.log(e)
                    message.error(e)
                }
                this.initData()
            }
        });
    }

    handleCashChange = () => {
        const {getFieldsValue, setFieldsValue} = this.props.form
        const {businessCaptialSetting, vwBusinessCashStat} = this.state
        const value = getFieldsValue(['cash'])
        if (value.cash > vwBusinessCashStat.cashSum) {
            message.error('提现金额不可大于可提现金额')
            return
        }
        const cashTure = accSub(value.cash, businessCaptialSetting.rate)
        setFieldsValue({
            cashTure: cashTure > 0 ? cashTure : 0
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form
        const {loading, businessCaptialSetting, bankInfos} = this.state
        const {inDlg} = this.props
        const formItemLayout = {
            labelCol: {
                xs: { span: 14 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 14 },
                sm: { span: inDlg? 14: 8 },
            },
        };
        return (
            <div>
                {this.renderAlertMessage()}
                <Form {...formItemLayout} onSubmit={this.handleSubmit} style={{marginTop: 20}}>
                    <Form.Item label={'提现金额'}>
                        {getFieldDecorator('cash', {
                            initialValue: '',
                            rules: [{ required: true, message: '请输入提现金额'}],
                        })(
                            <div>
                                <Input type={'number'} onBlur={this.handleCashChange}/>
                                <div>注:每笔提现手续费单笔{businessCaptialSetting.rate}元，直接在提现金额中扣除。</div>
                            </div>
                        )}
                    </Form.Item>
                    <Form.Item label={'到账金额'}>
                        {getFieldDecorator('cashTure', {
                            rules: [{ required: true, message: '请输入到账金额'}],
                        })(
                            <Input disabled/>
                        )}
                    </Form.Item>
                    <Form.Item label={'手续费'}>
                        {getFieldDecorator('rate', {
                            initialValue: businessCaptialSetting.rate,
                            rules: [{ required: true, message: '请输入手续费'}],
                        })(
                            <Input disabled/>
                        )}
                    </Form.Item>
                    {/*<Form.Item label={'请选择银行卡'}>*/}
                    {/*    {getFieldDecorator('card', {*/}
                    {/*        rules: [{ required: true, message: '请选择银行卡'}],*/}
                    {/*    })(*/}
                    {/*        <Select>*/}
                    {/*            {bankInfos.map(item => {*/}
                    {/*                return <Option key={item.bankId} value={item.bankId}>{item.bankName}/{item.bankNo}/{item.userName}</Option>*/}
                    {/*            })}*/}
                    {/*        </Select>*/}
                    {/*    )}*/}
                    {/*</Form.Item>*/}
                    <Form.Item label={'备注'}>
                        {getFieldDecorator('remark', {
                        })(
                            <Input />
                        )}
                    </Form.Item>
                    <Form.Item label={'登录密码'}>
                        {getFieldDecorator('password', {
                            rules: [{ required: true, message: '请输入登录密码'}],
                        })(
                            <Input type="password" autoComplete="off"/>
                        )}
                    </Form.Item>
                    <Form.Item {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit"  loading={loading}>
                            保存
                        </Button>
                    </Form.Item>
                </Form>
            </div>

        )
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Form.create()(SettlementApplyForm))
